import {
  Controller,
  Post,
  Get,
  UseInterceptors,
  UploadedFile,
  Body,
  Delete,
  Req
} from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { UploadService } from './upload.service'
import { UploadChunkDto } from './dto/uploadChunk.dto'
import { Request } from 'express'

@Controller('upload')
export class UploadController {
  constructor(private uploadService: UploadService) {}

  /**
   * 上传单个文件分片
   * @param file 文件分片数据
   * @param uploadChunkDto 分片信息(fileHash,chunkIndex等)
   * @param req 请求对象
   */
  @Post('chunk')
  @UseInterceptors(FileInterceptor('chunk'))
  async uploadChunk(
    @UploadedFile() file: Express.Multer.File,
    @Body() uploadChunkDto: UploadChunkDto,
    @Req() req: Request
  ) {
    const userId = req['user'].sub
    return this.uploadService.uploadChunk(file, uploadChunkDto, userId)
  }

  /**
   * 手动合并文件分片
   * @param body 包含fileHash、filename、totalChunks和parentId
   * @param req 请求对象
   */
  @Post('merge')
  async mergeChunks(
    @Body()
    body: {
      fileHash: string
      filename: string
      totalChunks: number
      parentId: number
    },
    @Req() req: Request
  ) {
    const userId = req['user'].sub
    return this.uploadService.mergeChunks(
      body.fileHash,
      body.filename,
      body.totalChunks,
      body.parentId,
      userId
    )
  }

  /**
   * 检查文件是否已存在(断点续传、秒传)
   * @param fileHash 文件哈希值
   * @param req 请求对象
   */
  @Post('check')
  async checkFile(@Body('fileHash') fileHash: string, @Req() req: Request) {
    const userId = req['user'].sub

    const uploadedChunks = await this.uploadService.getUploadedChunks(
      fileHash,
      userId
    )
    const { exists } = await this.uploadService.checkFileExists(
      fileHash,
      userId
    )
    return {
      exists,
      uploadedChunks
    }
  }

  /**
   * 取消文件上传，删除已上传的分片
   * @param fileHash 文件哈希值
   * @param req 请求对象
   */
  @Delete('cancel')
  async cancelUpload(@Body('fileHash') fileHash: string, @Req() req: Request) {
    const userId = req['user'].sub
    return this.uploadService.cancelUpload(fileHash, userId)
  }
}
